﻿using Himp.Platform.Client.Contracts;
using Himp.Platform.Client.Dals;
using Himp.Platform.Client.Models;
using ReaderB;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media.Animation;

namespace Himp.Platform.Client.Blls
{
    public class SamplePreparationBll
    {
        private int portFrmIndex = -1;
        private int fopencomport = -1;
        private byte readerAddr = 0xff;
        private byte[] SNR = new byte[4];

        private ISamplePreparationRecDal _samplePreparationRecDal;

        public SamplePreparationBll()
        {
            _samplePreparationRecDal = new SamplePreparationRecDal();
        }

        public async Task<string> WriteSamplePreparationRec(SamplePreparationRecCreateDto input)
        {
            if (!ConnectEqp())
            {
                return "连接写卡设备失败";
            }
            SetConfig();

            byte block = 0, errorCode = 0;
            byte[] data = new byte[16];
            int fCmdRet = 0x30;
            block = (byte)(2 * 4 + 0);

            string inputString = DateTime.Now.ToString("yyyyMMddHHmm00");

            switch (input.SampleType)
            {
                case 1: inputString += "61"; break;
                case 2: inputString += "62"; break;
                case 3: inputString += "31"; break;
                case 4: inputString += "21"; break;
                case 5: inputString += "22"; break;
            }

            string ascii32BitStr = AsciiToHex(inputString);

            if (ascii32BitStr.Length == 32)
            {
                data = HexStringToByteArray(ascii32BitStr);
            }

            fCmdRet = StaticClassReaderB.ISO14443AWrite(ref readerAddr, block, data, ref errorCode, portFrmIndex);

            if (fCmdRet == 0)
            {
                SamplePreparationRecModel samplePreparationRecModel = new SamplePreparationRecModel();
                samplePreparationRecModel.MachineCode = "手工";
                samplePreparationRecModel.AtuoSmapleFlag = 0;
                samplePreparationRecModel.SampleID = input.SampleID;
                samplePreparationRecModel.PackCode = inputString;
                samplePreparationRecModel.ZYWeight = input.SampleWeight;
                samplePreparationRecModel.ZYType = 0;
                samplePreparationRecModel.SampleType = input.SampleType;
                samplePreparationRecModel.Size = input.Size;
                samplePreparationRecModel.Water = 0;
                samplePreparationRecModel.EndTime = DateTime.Now;
                samplePreparationRecModel.SampleWeight = input.SampleWeight;
                samplePreparationRecModel.UserName = input.UserName;
                var msg = await _samplePreparationRecDal.HandleSamplePreparation(new List<SamplePreparationRecModel>() { samplePreparationRecModel });

                if (!string.IsNullOrEmpty(msg))
                {
                    return msg;
                }

                return "写卡成功";
            }
            else
            {
                return "写卡失败";
            }
        }

        // 将 ASCII 字符串转换为十六进制字符串的函数
        static string AsciiToHex(string asciiString)
        {
            // 使用 StringBuilder 来构建十六进制字符串
            StringBuilder hexBuilder = new StringBuilder();

            // 遍历 ASCII 字符串中的每个字符
            foreach (char c in asciiString)
            {
                // 获取字符的 ASCII 值
                int asciiValue = (int)c;

                // 将 ASCII 值转换为两位的十六进制字符串，并追加到 StringBuilder
                hexBuilder.Append(asciiValue.ToString("X2"));
            }

            // 返回最终的十六进制字符串
            return hexBuilder.ToString();
        }

        public void ReadSamplePreparationRec()
        {
            ConnectEqp();
            SetConfig();

            byte block, errorCode = 0;
            byte[] data = new byte[16];
            string temp;
            int fCmdRet = 0x30;
            block = (byte)(2 * 4);
            fCmdRet = StaticClassReaderB.ISO14443ARead(ref readerAddr, block, data, ref errorCode, portFrmIndex);

            if (fCmdRet == 0)
            {
                temp = ByteArrayToHexString(data).Replace(" ", "");
                MessageBox.Show(temp);
            }
        }

        private bool ConnectEqp()
        {
            Close();
            //读取配置值
            string ip = ConfigurationManager.AppSettings["EqpConnect"];
            readerAddr = Convert.ToByte("FF", 16); // $FF;
            int sRport = 6000;
            //string ip = "192.168.193.189";
            int port = Convert.ToInt32(sRport);
            int openresult = StaticClassReaderB.OpenNetPort(port, ip, ref readerAddr, ref portFrmIndex);

            if (openresult == 0)
            {
                fopencomport = portFrmIndex;
                return true;
            }

            return false;
        }

        private bool SetConfig()
        {
            int fCmdRet = 0x30;
            //14443A模式
            fCmdRet = StaticClassReaderB.ChangeTo14443A(ref readerAddr, portFrmIndex);
            //打开射频
            fCmdRet = StaticClassReaderB.OpenRf(ref readerAddr, portFrmIndex);
            //Request
            byte[] data = new byte[16];
            byte[] Data = new byte[2];
            byte errorCode = 0;
            fCmdRet = StaticClassReaderB.ISO14443ARequest(ref readerAddr, 1, Data, ref errorCode, portFrmIndex);
            //Anticoll
            byte reserved = 0;
            fCmdRet = StaticClassReaderB.ISO14443AAnticoll(ref readerAddr, reserved, SNR, ref errorCode, portFrmIndex);
            //Select
            byte size = 0;
            fCmdRet = StaticClassReaderB.ISO14443ASelect(ref readerAddr, SNR, ref size, ref errorCode, portFrmIndex);

            //AuthKey
            byte keyStyle = 0;
            byte[] key = new byte[5];
            string temp;
            byte accessSector = (byte)2;
            temp = "FFFFFFFFFFFF";
            key = HexStringToByteArray(temp);
            fCmdRet = StaticClassReaderB.ISO14443AAuthKey(ref readerAddr, keyStyle, accessSector, key, ref errorCode, portFrmIndex);

            return true;
        }

        private void Close()
        {
            if (portFrmIndex > 1023)
            {
                int fCmdRet = StaticClassReaderB.CloseNetPort(portFrmIndex);
                if (fCmdRet == 0)
                {
                    portFrmIndex = -1;
                    fopencomport = -1;
                }
            }
        }

        private byte[] HexStringToByteArray(string s)
        {
            s = s.Replace(" ", "");
            byte[] buffer = new byte[s.Length / 2];
            for (int i = 0; i < s.Length; i += 2)
                buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
            return buffer;
        }

        private string ByteArrayToHexString(byte[] data)
        {
            StringBuilder sb = new StringBuilder(data.Length * 3);
            foreach (byte b in data)
                sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
            return sb.ToString().ToUpper();
        }
    }
}
